package com.pw.study.tcp;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Author: linux_future
 * @since: 2022/3/30
 **/
public class TcpClientV2 {

    private static String appName="app";

    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            appName = args[1];
            System.out.println(args[0]);
        }
        System.out.println();
        Socket sc = new Socket("1.117.182.129", 6666);

        try (InputStream input = sc.getInputStream()) {
            try (OutputStream out = sc.getOutputStream()) {
                clientMsgHandler(input, out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        sc.close();
        System.out.println("client is closed ....");

    }

    private static void clientMsgHandler(InputStream input, OutputStream out) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(System.in);
        System.out.println("client <-- server: " + reader.readLine());
        for (; ; ) {
            System.out.print("client "+ appName+" >>>: ");
            String str = scanner.nextLine();
            writer.write(str);
            writer.newLine();
            writer.flush();
            String line = reader.readLine();
            System.out.println(appName+" <<< " + line);
            if (line.equals("bye")) {
                System.out.println("server is dead ....");
                break;
            }
        }

    }

}
